<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<el-row :gutter="20">
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
							<template #label>
								<WtmLabelTooltip label="属性名称" tooltip="物料属性的名称" />
							</template>
							<el-input v-model="stateData.vmModel.Entity.Name" disabled class="width100"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item
							ref="Entity_IsKeyAttribute_FormItem"
							prop="Entity.IsKeyAttribute"
							:rules="[{ required: true, message: '是否关键属性为必填项', trigger: 'blur' }]"
						>
							<template #label>
								<WtmLabelTooltip label="是否关键属性" tooltip="关键属性会生成SKU编码, 非关键属性仅用于采购和领用等辅助识别" />
							</template>
							<el-select v-model="stateData.vmModel.Entity.IsKeyAttribute" disabled class="width100">
								<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
								<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_MaterialId_FormItem" prop="Entity.MaterialId">
							<template #label>
								<WtmLabelTooltip label="物料" tooltip="关联的物料对象" />
							</template>
							<el-select v-model="stateData.vmModel.Entity.MaterialId" disabled class="width100">
								<el-option v-for="item in stateData.AllSysMaterials" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="12" class="mb20">
						<el-form-item ref="Entity_Order_FormItem" prop="Entity.Order" :rules="[{ required: true, message: '排序为必填项', trigger: 'blur' }]">
							<template #label>
								<WtmLabelTooltip label="排序" tooltip="物料属性的排序字段" />
							</template>
							<el-input-number v-model="stateData.vmModel.Entity.Order" disabled class="width100"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :lg="24" class="mb20">
						<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
							<template #label>
								<WtmLabelTooltip label="备注" tooltip="计量单位组的备注信息" />
							</template>
							<el-input type="textarea" :rows="3" v-model="stateData.vmModel.Entity.Remark" disabled></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>

		<!-- 属性值查看区域 -->
		<el-card v-if="stateData.vmModel.Entity.ID" shadow="hover" class="layout-padding-auto mt20">
			<template #header>
				<div class="card-header">
					<span class="card-header-title">属性值列表</span>
				</div>
			</template>

			<!-- 只读的属性值展示 -->
			<div class="mb20">
				<el-form-item>
					<template #label>
						<WtmLabelTooltip label="属性值" tooltip="该物料属性的所有属性值" />
					</template>
					<el-input-tag v-model="attributeValues" :tag-type="'primary'" :tag-effect="'plain'" :readonly="true" />
				</el-form-item>
				<el-alert v-if="attributeValues.length === 0" type="info" :closable="false" show-icon class="mt10">
					<template #default>
						<p style="margin: 0; font-size: 12px">暂无属性值</p>
					</template>
				</el-alert>
			</div>
		</el-card>
	</div>
</template>

<!--suppress JSAnnotator -->
<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, ComponentInternalInstance } from 'vue';
import { SysMaterialAttributeApi as api } from '/@/views/supplychain/sysmaterialattribute/api';
import { SysMaterialAttributeValueApi as attributeValueApi } from '/@/views/supplychain/sysmaterialattributevalue/api';
import other from '/@/utils/other';
import { ISysMaterialAttributeVm } from '/@/views/supplychain/sysmaterialattribute/api/interface';
import { ISysSelectType, IViewModel } from '/@/types/common';

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	AGREE: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;
const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const activeTab = ref('main');
const attributeValues = ref<string[]>([]); // 属性值标签列表（只读）

const stateData = reactive<IViewModel<ISysMaterialAttributeVm>>({
	vmModel: {
		Entity: {
			ID: null,
			Name: null,
			IsKeyAttribute: false,
			MaterialId: null,
			Remark: null,
			Order: null,
		},

		ActionName: null,
		IsMyApprove: null,
	},
	AllSysMaterials: [] as ISysSelectType[],
});

// 取消
const onClose = () => {
	closeDialog();
};

// 加载现有的属性值
const loadExistingAttributeValues = async () => {
	if (!stateData.vmModel.Entity.ID) return;

	try {
		const response = await attributeValueApi().search({
			AttributeId: stateData.vmModel.Entity.ID,
			PageIndex: 1,
			PageSize: 1000,
		});

		// 清空现有数据
		attributeValues.value = [];

		// 处理响应数据
		let dataList: any[] = [];
		if (response.Data) {
			// 可能是直接的数组
			if (Array.isArray(response.Data)) {
				dataList = response.Data;
			}
		}

		// 加载数据
		dataList.forEach((item: any) => {
			if (item.Value) {
				attributeValues.value.push(item.Value);
			}
		});
	} catch (error) {
		console.error('加载属性值失败:', error);
	}
};

// 加载选择列表数据
const loadData = async () => {
	await Promise.allSettled([
		other.getSelectList('/api/SysMaterialAttribute/GetSysMaterials', [], false).then((x) => (stateData.AllSysMaterials = x)),
		api()
			.get(stateData.vmModel.Entity.ID ?? '')
			.then((x) => other.setValue(stateData.vmModel, x)),
	]);
};

const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	}
};
// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 并行加载选择列表数据
		await loadData();
		// 加载现有的属性值
		if (stateData.vmModel.Entity.ID) {
			await loadExistingAttributeValues();
		}
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];
	emit('updateHeaderButtons', headerButtons);
};
</script>

<style scoped lang="scss">
.mt10 {
	margin-top: 10px;
}

.mt20 {
	margin-top: 20px;
}

.mb20 {
	margin-bottom: 20px;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;

	.card-header-title {
		font-size: 16px;
		font-weight: 600;
		color: #303133;
	}
}

:deep(.el-alert__content) {
	p {
		margin: 0;
		line-height: 1.6;
	}
}

:deep(.el-input-tag) {
	width: 100%;
}
</style>
